//@sourceURL=weixin_grabber.js
function ($) {
    var inputTxtSelector = '#textInput';
    var sendBtnSelector = '.inputArea .chatSend';
    var mediaBlockSelector = 'div.media.mediaFullText';
    var articleTitleSelector = '.mediaHead .title';
    var articleLinkSelector = 'a[href^="http://mp.weixin.qq.com/mp/appmsg/show?"]';
    window.console = window.console || {log: function () {
    }};

    var getCommandList = function () {
        var list = ['0000'];
        for (var i = 0; i < 70; i++) {
            list.push('0' + (i > 9 ? i : '0' + i ));
        }
        for (var i = 1; i < 14; i++) {
            list.push('a' + i);
        }
        for (var i = 1; i < 4; i++) {
            list.push('b' + i);
        }
        return list;
    }

    window.articleUrls = [];

    var duration = 5000;//根据网速决定长短，也可以自己写一个检测是否收到响应的函数（或代码）
    var sendCmd = function (cmdList, linkContainer, tryTime) {
        var cmd = cmdList.shift();
        tryTime = tryTime || 1;
        console.log('sending:' + cmd + "...");
        if (tryTime < 2) {
            $(inputTxtSelector).val(cmd);
            $(sendBtnSelector).click();
        } else {
            console.log('trying ' + tryTime + '(ed) time');
        }
        if (cmdList.length) {
            var arg = arguments;
            setTimeout(function () {
                console.log("ready to send...");
                var isOk = collectArticleInfo(cmd, linkContainer);
                if (!isOk && tryTime <= 5) {
                    cmdList.unshift(cmd);
                    tryTime++;
                } else {
                    if (tryTime > 5) {
                        console.log('try time > 5,give up:' + cmd);
                        tryTime = 1;
                    }
                }
                arg.callee.call(null, cmdList, linkContainer, tryTime);
            }, duration);
        } else {
//			showArticleLnks();
            console.log('send cmd over!');
        }
    }

    var parseAllRespItemToArticles = function (linkContainer) {
        var chatRespItems = $('.chatItem.you');
        chatRespItems.each(function () {
            var respItem = $(this);
            var articles = parseRespItemToArtices(respItem);
            showArticleInfoToLinkContainer(null, articles, linkContainer);
        });
    }

    var parseRespItemToArtices = function (respItem) {
        var mediaHeadTitle = respItem.find('.mediaHead .title');
        var mesgTitleTitle = respItem.find('.mediaPanel .mesgTitleTitle');
        var articles = [];
        if (mediaHeadTitle.length) {
            var title = mediaHeadTitle.text();
            var article = {};
            article.title = $.trim(title);
            article.url = mediaHeadTitle.closest(articleLinkSelector).attr('href');
            articles.push(article);
        } else if (mesgTitleTitle.length) {
            var title0 = mesgTitleTitle.text();
            var article0 = {};
            article0.title = $.trim(title0);
            article0.url = mesgTitleTitle.closest(articleLinkSelector).attr('href');
            articles.push(article0);
            var mediaPanel = mesgTitleTitle.closest('.mediaPanel');
            var links = mediaPanel.find('.mediaContent').find(articleLinkSelector);
            links.each(function (argument) {
                var link = $(this);
                var article = {};
                article.url = link.attr('href');
                article.title = $.trim(link.find('.mediaMesgTitle').text());
                articles.push(article);
            });
        }

        return articles;
    }

    var showArticleInfoToLinkContainer = function (cmd, articles, linkContainer) {
//        arguments.length == 2 && (linkContainer = articles) &&(articles = cmd);
        var textArea = linkContainer.find('textarea');
        var str = cmd ? cmd + ":\n" : '';
        for (var i = 0; i < articles.length; i++) {
            var article = articles[i];
            str += article.title + ': ' + article.url;
            str += '\n';
        }
        str += "\n";

        var text = textArea.val();
        text += str;
        textArea.val(text);
    }

    var collectArticleInfo = function (cmd, linkContainer) {
        var isOk = true;
        var cmdChatContent = $('.chatItem.me').find('.cloudContent').filter(function () {
            return $.trim($(this).text()) == cmd;
        });
        if (cmdChatContent.length) {
            cmdChatContent = cmdChatContent.eq(0);
            var cmdChatItem = cmdChatContent.closest('.chatItem.me');
            var cmdChatRespItem = cmdChatItem.next(".chatItem.you");
            if (cmdChatRespItem.length) {
                var articles = parseRespItemToArtices(cmdChatRespItem);
                showArticleInfoToLinkContainer(cmd, articles, linkContainer);
            } else {
                console.log('cmd:' + cmd + ' response is not ok');
                isOk = false;
            }
        } else {
            console.log('cmd:' + cmd + ' send not ok');
            isOk = false;
        }

        return isOk;
    }

    var makeLinkContainer = function (argument) {
        var div = $('<div/>').css({
            position: 'fixed',
            right: 0,
            top: 0,
            width: '50%',
            height: '90%',
            'z-index': 0
        });


        var btnCss = {
            position: 'absolute',
            right: 0,
            top: '5px'
        };

        var remove  = function () {
            div.remove();
        }
        var prev = div.$prev = function (argument) {
            div.css('z-index', 9999);
        }
        var backend = div.$backend = function (argument) {
            div.css('z-index', 0);
        }

        var closeBtn = $('<button/>').text('关闭').css(btnCss).on('click',remove);

        var prevBtn = $('<button/>').text('前置').css(btnCss).css('right','80px').on('click', prev);

        var backendBtn = $('<button/>').text('后置').css(btnCss).css('right','40px').on('click', backend);

        var textArea = $('<textarea/>').css({
            width: '100%',
            height: '100%'
        });

        div.append(textArea).append(prevBtn).append(backendBtn).append(closeBtn);
        return div;
    }

    var linkContainer = makeLinkContainer();
    var articleCommandList = getCommandList();
    window.cmdList = articleCommandList;
    if (window.cmdList && window.cmdList.length) {
        sendCmd(window.cmdList, linkContainer);
    } else {
        parseAllRespItemToArticles(linkContainer);
    }

    linkContainer.appendTo('body');
    setTimeout(function(){
        linkContainer.$prev();
    },25*1000);
};